package com.cke.yang.security.infra.filter;

import com.cke.yang.common.domain.model.SecUserDetails;
import com.cke.yang.common.infra.utils.JwtUtils;
import com.cke.yang.security.app.service.SecRoleService;
import com.cke.yang.security.domain.entity.SecRole;
import com.cke.yang.security.domain.repository.SecUserRepository;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.List;

/**
 * JWT认证过滤器
 */
@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private SecUserRepository userRepository;

    @Autowired
    private SecRoleService secRoleService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        try {
            String jwt = getJwtFromRequest(request);

            if (StringUtils.hasText(jwt) && !jwtUtils.isTokenExpired(jwt)) {
                String username = jwtUtils.getUsernameFromToken(jwt);
                Long roleIdFromToken = jwtUtils.getRoleIdFromToken(jwt);

                if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                    UserDetails userDetails = userRepository.findByUsername(username).orElse(null);

                    if (userDetails != null && jwtUtils.validateToken(jwt, username)) {

                        UsernamePasswordAuthenticationToken authentication =
                                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        SecurityContextHolder.getContext().setAuthentication(authentication);

                        // 如果是 SecUserDetails 且 token 中包含角色ID，则填充角色信息
                        if (userDetails instanceof SecUserDetails secUserDetails && roleIdFromToken != null) {

                            // 验证用户是否拥有该角色
                            List<SecRole> userRoles = secRoleService.getCurrentUserRoles();
                            SecRole tokenRole = userRoles.stream()
                                    .filter(role -> role.getRoleId().equals(roleIdFromToken))
                                    .findFirst()
                                    .orElse(null);

                            if (tokenRole != null) {
                                secUserDetails.setCurrentRoleId(tokenRole.getRoleId());
                                secUserDetails.setCurrentRoleName(tokenRole.getRoleName());
                                log.debug("从JWT token中恢复用户 {} 的角色: {} (ID: {})",
                                        username, tokenRole.getRoleName(), tokenRole.getRoleId());
                            } else {
                                log.warn("JWT token中的角色ID {} 对用户 {} 无效", roleIdFromToken, username);
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) {
            log.error("Could not set user authentication in security context", ex);
        }

        filterChain.doFilter(request, response);
    }

    private String getJwtFromRequest(HttpServletRequest request) {
        // 首先尝试从 Authorization Header 获取 JWT token
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }

        // 如果 Header 中没有，则尝试从 URL 参数 accessToken 获取
        String accessToken = request.getParameter("accessToken");
        if (StringUtils.hasText(accessToken)) {
            return accessToken;
        }

        return null;
    }
}
